//
//  HMPhoto.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/8/3.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import Foundation
import UIKit
import IDMPhotoBrowser
import TZImagePickerController
//import Tactile

@objc protocol HMPhotoDelegate: class {
 //   func photoImagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool)
//   @objc optional func photoImages(photos:[UIImage]! , sign: String?)

   @objc optional func photoImagesAndAssets(photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool , sign: String?)
    
}


class HMPhoto: NSObject {
//    var photos : [UIImage]?
    public var sign: String = ""
    var allowCrop: Bool = false
    weak var delegate : HMPhotoDelegate?
   
    /// 先 调用 pushTZImagePickerController 创建的对象， 再用didFinishPickingPhotosHandle 回调
    var hmImagePickerVc: TZImagePickerController?
    
    var selectedPhotos = NSMutableArray() // 选择的按钮的个数,按数据+1 - 保存到数据
    var selectedAssets = NSMutableArray()
    var maxCount: Int = 1 ///< 照片最大可选张数，设置为1即为单选模式
    var columnNumber: Int = 0
    var location: CLLocation?
    var imagePickerVc: UIImagePickerController?
    var margin: CGFloat = 0
    var itemWH: CGFloat = 0
    var isOpenStorage: Bool = false  // 是否打开存储对象（用来多选择时用的）
    var isSelectOriginalPhoto: Bool  = false
    var urls = Array<String>()  //上传之后z转url
    /// 获取自身实例
    static let shareInstance: HMPhoto = {
        let instance = HMPhoto()
        return instance
    }()
    
    class func showPhotoBrowser(urls: String, index: Int) {
        let array = urls.components(separatedBy: ";")
        showPhotoBrowser(urls: array, index: index)
        
    }
    
    class func showPhotoBrowser(urls: [String], index: Int) {
        var photos:[IDMPhoto] = []
        
        for url in urls {
            if url == "" {
                continue
            }
            //            let uuu = URL(string: url)
            if let photo = IDMPhoto(url: URL(string: url)) {
                photos.append(photo)
            }
        }
        if let browser = IDMPhotoBrowser(photos: photos) {
            browser.dismissOnTouch = true
            browser.displayDoneButton = false
            browser.displayActionButton = false
            browser.usePopAnimation = true
            let idx = UInt(index)
            browser.setInitialPageIndex(idx)
            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                vc.present(browser, animated: true) {
                    //
                }
            }
        }
    }
}

public extension UIView {
    /// 添加事件
    func addTapGesture(target:Any?, action: Selector) {
        let gesture = UITapGestureRecognizer(target: target, action: action)
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(gesture)
    }
    
    
}


/// pragma mark - TZImagePickerControllerDelegate
extension HMPhoto : TZImagePickerControllerDelegate {
    public func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: Any!) {
        print(" ---->>视频  didFinishPickingVideo")
    }
    
    public func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingGifImage animatedImage: UIImage!, sourceAssets asset: Any!) {
        print("---->>动态图片 didFinishPickingGifImage")
    }
    
    public func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        //保存到对象内存
        if isOpenStorage == true  {
            self.selectedPhotos = NSMutableArray.init(array: photos)
            self.selectedAssets = NSMutableArray.init(array: assets)
            self.isSelectOriginalPhoto = isSelectOriginalPhoto
        }else {
//           self.selectedPhotos = NSMutableArray.init()
//           self.selectedAssets = NSMutableArray.init()
        }

        
        

            if photos.count > 0 {
                
                var datas: [Data]?
                var imgsStr: [String]?
                for i in 0..<photos.count {
                    let dataImg: Data = UIImage.compressImageSize(image:photos[i]) as Data
                    let originalImgSize = dataImg.count/1024 as Int  //获取图片大小
                    print("id: \(i) 原始大小: \(originalImgSize)")
                    imgsStr?.append("图片\(i)")
                    datas?.append(dataImg)
                }
                

                self.delegate?.photoImagesAndAssets?(photos: photos, assets: assets, isSelectOriginalPhoto: isSelectOriginalPhoto , sign: self.sign)
            }else {
                //照片为空
            }

        picker.dismiss(animated: true) {
            
        }
    }
    
    /// 用户点击了取消
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("---->cancel")
    }
    
    /// 打印图片名字
    func printAssetsName(assets :NSArray) {
        var hmFileName: String = ""
        
        for asset in assets {
            let ass = asset as! PHAsset
            hmFileName = ass.value(forKey: "filename") as! String
            // 2.图片位置信息
            print("location ->>",ass.location!)
            print("fileName ->>\(hmFileName)")
        }

    }
}



extension HMPhoto {
    /// 拍照
    func takePhoto(_ target: Any?) {
      let authStatus :AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        
        let _tar =  target as! UIViewController //转
        
        if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
             // 无相机权限 做一个友好的提示
            let alert = UIAlertController(title: "无法使用相机", message: "请在iPhone的 \"设置-隐私-相机\" 中允许访问相机", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (alertAction) in
                
            })
            alert.addAction(action)
            _tar.present(alert, animated: true, completion: nil)
            
        }else if authStatus == AVAuthorizationStatus.notDetermined {
             // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
            AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
                if granted {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self takePhoto];
//                        });
                }
            }
            
        }else if PHPhotoLibrary.authorizationStatus().rawValue == 2 {
            let alert = UIAlertController(title: "无法访问相册", message: "请在iPhone的\"设置-隐私-相册\"中允许访问相册", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (alertAction) in
                ///
            })
            alert.addAction(action)
            _tar.present(alert, animated: true, completion: nil)
            
        }else if PHPhotoLibrary.authorizationStatus().rawValue == 0 { // 未请求过相册权限
            TZImageManager.default()?.requestAuthorization(completion: {
                 self.takePhoto(target)
            })
        }else {
            self.pushImagePickerController(target: target)
        }
    }
    
    /// 调用相机
    func pushImagePickerController(target: Any?) {
        //定位
        TZLocationManager().startLocation(successBlock: { (locations) in
            print("locations?.first---->\(locations?.first)")
           self.location = locations?.first
            
        }) { (error) in
            print("error---->\(String(describing: error))")
            self.location = nil
        }
        
        let sourceType = UIImagePickerControllerSourceType.camera
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
//            self.image
        }
        
    }
    
    /// 预览照片 -- 返回一个预览用的 TZImagePickerController 对象
    func showImagePickerController(_ target: Any?, photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool, index: NSInteger)  -> TZImagePickerController{
        let mutableAssets = NSMutableArray.init(array: assets)
        let mutablePhotos = NSMutableArray.init(array: photos)
        
        let imagePickerVc: TZImagePickerController = TZImagePickerController.init(selectedAssets: mutableAssets, selectedPhotos: mutablePhotos, index: index)
        imagePickerVc.maxImagesCount = HMPhoto.shareInstance.maxCount
        imagePickerVc.allowPickingGif = false
        imagePickerVc.allowPickingOriginalPhoto = true
        imagePickerVc.allowPickingMultipleVideo = false
        imagePickerVc.showSelectedIndex = true
        imagePickerVc.isSelectOriginalPhoto = HMPhoto.shareInstance.isSelectOriginalPhoto
//        imagePickerVc.didFinishPickingPhotosHandle = {
//            (photos, assets, isSelectOriginalPhoto) -> () in
//            //回调
////            self.aSelectedPhotos  = NSMutableArray.init(array: photos!)
////            self.aSelectedAssets = NSMutableArray.init(array: assets!)
////            self.aIsSelectOriginalPhoto = isSelectOriginalPhoto
////            self.aCollectionView?.reloadData()
////            self.aCollectionView?.contentSize = CGSize.init(width: 0, height: ((CGFloat(self.aSelectedPhotos.count) + 2.0) / 3.0) * (self.aMargin + self.aItemWH))
//        }
        
        let  vc = target as! UIViewController
        vc.present(imagePickerVc, animated: true, completion: nil)
        return imagePickerVc
    }
    
    
    /// 
    func getImagePickerVc(_ target: Any?) -> UIImagePickerController {
        let tar: UIViewController = target as! UIViewController
        if self.imagePickerVc == nil {
            imagePickerVc = UIImagePickerController()
            imagePickerVc?.delegate = HMPhoto.shareInstance
            imagePickerVc?.navigationBar.barTintColor = tar.navigationController?.navigationBar.tintColor
            let tzBarItem: UIBarButtonItem
            let BarItem : UIBarButtonItem
//            if #available(iOS 9,  *) {
//                tzBarItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [TZImagePickerController.classForCoder() as! UIAppearanceContainer.Type])
//
//                BarItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIImagePickerController.classForCoder()])
//            }else {
//                tzBarItem = UIBarButtonItem.appearance(for: <#T##UITraitCollection#>, whenContainedInInstancesOf: <#T##[UIAppearanceContainer.Type]#>)
//            }
        }
        return imagePickerVc!
        
    }
    
    
    ///  BOOL _isSelectOriginalPhoto; /// 每次调用会重新创建一个 imagePickerVc 对象
    func pushTZImagePickerController(_ target:Any?,  max: Int, column: Int,  isSelectOriginal: Bool) {
        self.maxCount = max
        self.columnNumber = column
        if maxCount <= 0 {
            return
        }
    
        
        let imagePickerVc = TZImagePickerController.init(maxImagesCount: max, columnNumber: column, delegate: HMPhoto.shareInstance, pushPhotoPickerVc: true)
        
        
        /// pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
        imagePickerVc?.isSelectOriginalPhoto = isSelectOriginal
        self.isSelectOriginalPhoto = isSelectOriginal
        
        if maxCount > 1 {
               // 1.设置目前已经选中的图片数组
            imagePickerVc?.selectedAssets =  HMPhoto.shareInstance.selectedAssets  // 目前已经选中的图片数组
        }
        // 在内部显示拍照按钮
        imagePickerVc?.allowTakePicture = true
        // 在内部显示拍视频按
        imagePickerVc?.allowTakeVideo = false
        // 视频最大拍摄时间
        imagePickerVc?.videoMaximumDuration = 10
        imagePickerVc?.uiImagePickerControllerSettingBlock = {
            (imagePickerController : UIImagePickerController!) -> ()in
            imagePickerController.videoQuality = UIImagePickerControllerQualityType.typeHigh
        }
        
        ///2. 在这里设置imagePickerVc的外观
        imagePickerVc?.iconThemeColor = .red
        imagePickerVc?.showPhotoCannotSelectLayer = true
        imagePickerVc?.cannotSelectLayerColor = UIColor.white.withAlphaComponent(0.8)
//        imagePickerVc?.photoPickerPageUIConfigBlock = {
//         (collectionView: UICollectionView!, bottomToolBar: UIButton!, previewButton: UIButton!, originalPhotoButton: UIButton!, originalPhotoLabel: UILabel!, doneButton: UIButton!, numberImageView: UIImageView!, numberLabel: UILabel!, divideLine: UIView!) -> () in
//                 doneButton!.setTitleColor(.red, for: .normal)
//            } as! (UICollectionView, UIView, UIButton, UIButton, UILabel, UIButton, UIImageView, UILabel, UIView) -> ()
        

        /// 3. 设置是否可以选择视频/图片/原图
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingImage = true
        imagePickerVc?.allowPickingGif = false
        imagePickerVc?.allowPickingOriginalPhoto = true
        imagePickerVc?.allowPickingMultipleVideo = false
        /// 4. 照片排列按修改时间升序
        imagePickerVc?.sortAscendingByModificationDate = false
        
        /// 5. 单选模式,maxImagesCount为1时才生效
         imagePickerVc?.showSelectBtn = false
         imagePickerVc?.allowCrop = HMPhoto.shareInstance.allowCrop
         imagePickerVc?.needCircleCrop = false
        // 设置竖屏下的裁剪尺寸
        let left: NSInteger = 30
        let widthHeight: NSInteger = Int(configure.shareConfigure.screenWidth) - 2 * left
        let top: NSInteger = (Int(configure.shareConfigure.screenHeight) - widthHeight) / 2
        imagePickerVc?.cropRect = CGRect.init(x: left, y: top, width: widthHeight, height: widthHeight)
        
         // 设置是否显示图片序号
        imagePickerVc?.showSelectedIndex = true
        
        
        self.hmImagePickerVc = imagePickerVc!
//        /// 你可以通过block或者代理，来得到用户选择的照片.
//        imagePickerVc?.didFinishPickingPhotosHandle = {
//            (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
//            print("======>>", assets)
//            self.selectedPhotos = NSMutableArray.init(array: photos)
//            self.selectedAssets = NSMutableArray.init(array: assets)
//            self.delegate?.photoImagesAndAssets?(photos: photos, assets: assets, isSelectOriginalPhoto: isSelectOriginalPhoto)
//        }
//
        let  vc = target as! UIViewController
        vc.present(imagePickerVc!, animated: true, completion: nil)
    }
}


extension HMPhoto: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
}

// 暂时没什么用
extension HMPhoto {
    /// 上传头像 --- 统一需要上传头像
    /// reurn url
    class func requestImages(photos:[UIImage]!) {
       
        
        for image in photos {
//            print("-------->>", image)
            let zipImageData: Data = UIImageJPEGRepresentation(image, 0.2)!

            let _date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateString = formatter.string(from: _date)

            NetRequestTool.shareInstance.met = .post
            NetRequestTool.upload(url: "/user/image/upload", data:[zipImageData] ,imgName: [dateString] ,parameters: [:], success: { (json) in
    //            self.portraitUrl =
                  HMPhoto.shareInstance.urls.append(json["url"].stringValue)
            }) { (err, msg) in
                print("---d-d-d-d-d-d-d-d", err, msg)
            }

        }
        
        
        
//        return urls
 
        
    }
    
    ///  压缩图片 及  UIImage 转 Data
    class func requestHeadImages(photos: [UIImage]!, assets: [Any]?) -> (datas: [Data], imgAssets: [Any]){
//        var urls: [String]?
        let _date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateString = formatter.string(from: _date)
        
        let datas  = NSMutableArray()
        let imgAssets = NSMutableArray()
        var i = 0
        for photo in photos {
            print("------>",photo)
            let zipImageData: Data = UIImageJPEGRepresentation(photos[i], 0.2)!
            let str = "\(dateString)-\(i)"
            imgAssets.add(str)
            datas.add(zipImageData)
            i += 1
        }
        
//        NetRequestTool.shareInstance.met = .post
//        NetRequestTool.upload(url: "/user/image/upload", data:datas as! [Data] ,imgName:imgAssets as! [String] ,parameters: [:], success: { (json) in
////            self.portraitUrl =
//
//        }) { (err, msg) in
//            print("---d-d-d-d-d-d-d-d", err, msg)
//        }
//
        return (datas as! [Data], imgAssets as! [Any])
    }

    
    
    
    
    // 返回一个容器控制器
    class func createCollectionView() -> UICollectionView {
        
        let layout = UICollectionViewLayout()
        let coll = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        coll.backgroundColor = UIColor.clear
        coll.isScrollEnabled = false
        coll.alwaysBounceVertical = true
        coll.contentInset = UIEdgeInsetsMake(4, 4, 4, 4)
        return coll
    }
}
